<?php

namespace App\Service\CallingCards;

use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Models\Common\ConfigModel;
use App\Models\Common\FsOrganizationModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class FeishuApiService
{
    public static function accessToken(array $forceConfig = [])
    {
        if ($forceConfig) {
            $app_id     = $forceConfig['appID'] ?? '';
            $app_secret = $forceConfig['AppSecret'] ?? '';
        } else {

            // callingcard专用
            $config     = ConfigModel::getFsConfigByPlatformNameOrgId(UserPermissionAuth::MODULE_CALLING_CARD, 0);
            $app_id     = $config['appId'] ?? '';
            $app_secret = $config['appSecret'] ?? '';
        }

        $cacheKey   = "feishu_access_token_{$app_id}";
        $body       = Cache::get($cacheKey);
        if (null !== $body) {
            return $body;
        }
        $response = Http::withHeaders([
            'Content-Type' => 'application/json; charset=utf-8',
        ])->post(
            'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal',
            compact('app_id', 'app_secret')
        );
        $arr      = json_decode($response->body(), true);
        if (JSON_ERROR_NONE !== json_last_error()) {
            return '';
        }
        $body = $arr['app_access_token'];
        Cache::put($cacheKey, $body, max(0, $arr['expire'] - 60));
        Cache::put("feishu_tenant_access_token_{$app_id}", $arr['tenant_access_token'], max(0, $arr['expire'] - 60));
        return $body;
    }

    public static function loginByCode(string $code)
    {
        /**
        [
            "code" => 0
            "msg" => "success"
            "data" => array:8 [
                "access_token" => "u-gusDkUIvmYH0C1DQtKZy9e"
                "employee_id" => "g18e5a8f"
                "expires_in" => 1643256300
                "open_id" => "ou_c90f808b045a43f97990bd2a1fd0707b"
                "refresh_token" => "ur-K9SpECtrNG4UC0OoqKzmkc"
                "session_key" => "759c3cfba3065b3dcd35326ff3ea936e"
                "tenant_key" => "13a5aac7558d5740"
                "union_id" => "ou_eb261923e1806da1bb43fc4bb339da95"
            ]
        ]
         */
        return Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->withToken(static::accessToken())
            ->post('https://open.feishu.cn/open-apis/mina/v2/tokenLoginValidate', [
                'grant_type' => 'authorization_code',
                'code'       => $code,
            ])->json();
    }

    public static function userInfo(string $openid, string $user_access_token)
    {
        /**
        [
            "code" => 0
            "data" => array:1 [
                "user" => array:23 [
                    "avatar" => array:4 [
                        "avatar_240" => "https://s1-imfile.feishucdn.com/static-resource/v1/v2_723a7c16-a366-4f9a-8d41-cfe3ac979a5g~?image_size=240x240&cut_type=&quality=&format=png&sticker_format=.webp"
                        "avatar_640" => "https://s1-imfile.feishucdn.com/static-resource/v1/v2_723a7c16-a366-4f9a-8d41-cfe3ac979a5g~?image_size=640x640&cut_type=&quality=&format=png&sticker_format=.webp"
                        "avatar_72" => "https://s1-imfile.feishucdn.com/static-resource/v1/v2_723a7c16-a366-4f9a-8d41-cfe3ac979a5g~?image_size=72x72&cut_type=&quality=&format=png&sticker_format=.webp"
                        "avatar_origin" => "https://s1-imfile.feishucdn.com/static-resource/v1/v2_723a7c16-a366-4f9a-8d41-cfe3ac979a5g~?image_size=noop&cut_type=&quality=&format=png&sticker_format=.webp"
                    ]
                    "city" => "上海"
                    "country" => ""
                    "custom_attrs" => []
                    "department_ids" => array:1 [
                        0 => "od-5937a115f5e23b277dcef6eac5b018aa"
                    ]
                    "description" => ""
                    "employee_no" => "0622"
                    "employee_type" => 1
                    "en_name" => ""
                    "gender" => 0
                    "is_tenant_manager" => false
                    "job_title" => "前端开发工程师"
                    "join_time" => 1637510400
                    "leader_user_id" => "ou_e675415a797fdaa30523cdeeec06da66"
                    "mobile" => "+8618651546985"
                    "mobile_visible" => true
                    "name" => "陈康华（星魂）"
                    "open_id" => "ou_c90f808b045a43f97990bd2a1fd0707b"
                    "orders" => array:1 [
                        0 => array:3 [
                            "department_id" => "od-5937a115f5e23b277dcef6eac5b018aa"
                            "department_order" => 1
                            "user_order" => 0
                        ]
                    ]
                    "status" => array:5 [
                        "is_activated" => true
                        "is_exited" => false
                        "is_frozen" => false
                        "is_resigned" => false
                        "is_unjoin" => false
                    ]
                    "union_id" => "on_4e0975efd84c5d9da14d8cd785097af4"
                    "user_id" => "g18e5a8f"
                    "work_station" => ""
                ]
            ]
            "msg" => "success"
        ]
         */
        return Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->withToken($user_access_token)
            ->get('https://open.feishu.cn/open-apis/contact/v3/users/' . $openid)
            ->json();
    }

    public static function getDepartmentName($department_ids)
    {
        if (!count($department_ids)) {
            return '';
        }
        $departmentInfo = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
        ->withToken(static::accessToken())
        ->get('https://open.feishu.cn/open-apis/contact/v3/departments/parent', [
            'department_id' => $department_ids[0],
        ])->json();

        if (!isset($departmentInfo['code']) || !isset($departmentInfo['data']['items'])) {
            return '';
        }

        if ($departmentInfo['code'] != 0) {
            return '';
        }

        $departmentName = '';
        foreach ($departmentInfo['data']['items'] as $item) {
            if ($item['parent_department_id'] == 0) {
                $departmentName = $item['name'];
            }
        }
        return $departmentName;
    }

    public static function getDepartment($departmentId)
    {
        if (!mb_strlen($departmentId)) {
            return '';
        }
        return  Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->withToken(self::accessToken())
            ->get('https://open.feishu.cn/open-apis/contact/v3/departments/' . $departmentId)->json();
    }

    //通过ID获取用户信息
    public static function getUserInfoByFeishuId($feishuId)
    {
        return Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->withToken(static::accessToken())
            ->get('https://open.feishu.cn/open-apis/contact/v3/users/' . $feishuId, ['user_id_type' => 'user_id'])->json();
    }

    /**
     * 获取供应商的部门列表
     * @param string $pDepartmentId 父级部门id，根目录=0
     * @param string $pageToken    分页token
     * @return array
     */
    public static function getSupplierDepartments(int $organizationId, string $pDepartmentId, string $pageToken = ''): array
    {
        if (!$organizationId) {
            throw new \Exception("getSupplierDepartments.organizationId = 0, pDepartmentId = {$pDepartmentId}");
        }

        $forceConfig = FsOrganizationModel::getApiConfig($organizationId);

        return Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                   ->withToken(self::accessToken($forceConfig))
                   ->get("https://open.feishu.cn/open-apis/contact/v3/departments",
                       ['page_size' => 50, 'fetch_child' => false, 'parent_department_id' => "{$pDepartmentId}", 'page_token' => $pageToken])
                   ->json();
    }

    /**
     * 获取部门下的用户列表
     * @param string $departmentId
     * @return array
     */
    public static function getUserInDepartments(int $organizationId, string $openDepartmentId, string $pageToken = ''): array
    {
        $forceConfig = FsOrganizationModel::getApiConfig($organizationId);

        return Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->withToken(self::accessToken($forceConfig))
                   ->get('https://open.feishu.cn/open-apis/contact/v3/users/find_by_department', [
                       'department_id' => $openDepartmentId,
                       'page_size'     => 50,
                       'page_token'    => $pageToken
                   ])->json();
    }
}
